#include <windows.h>
#include <stdarg.h>
#include <stdio.h>
#include <assert.h>

#include "trace.h"

/////////////////////////////////////////////////////////////////////////////
// Diagnostic Trace
#ifdef _DEBUG
// determine number of elements in an array (not bytes)
#define _countof(array) (sizeof(array)/sizeof(array[0]))

#ifdef __cplusplus
extern "C" {
#endif

void Trace(const char * lpszFormat, ...)
{
	int nBuf;
	TCHAR szBuffer[512];

#ifndef _DEBUG 
	return;
#endif

	va_list args;
	va_start(args, lpszFormat);


	nBuf = _vsnprintf(szBuffer, _countof(szBuffer), lpszFormat, args);

	// was there an error? was the expanded string too long?
	assert(nBuf >= 0);

	OutputDebugString(szBuffer);

	va_end(args);
}

void TraceLastError(void)
{
	LPVOID lpMsgBuf;

#ifndef _DEBUG 
	return;
#endif

	FormatMessage( 
		FORMAT_MESSAGE_ALLOCATE_BUFFER | 
		FORMAT_MESSAGE_FROM_SYSTEM | 
		FORMAT_MESSAGE_IGNORE_INSERTS,
		NULL,
		GetLastError(),
		MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language
		(LPTSTR) &lpMsgBuf,
		0,
		NULL 
		);

	Trace((char *)lpMsgBuf);
	LocalFree( lpMsgBuf );
}

#ifdef __cplusplus
}
#endif

#endif //_DEBUG

/////////////////////////////////////////////////////////////////////////////
